package com.applink.sell_proof.utilXMLParser;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.content.Context;

import com.applink.sell_proof.R;

public class AndroidUIParser {
	
		private static final String strEditText = "EditText";
		private static final String strItem = "item";
		private static final String ANDROID_ID = "android:id";
		private static final String LAYOUT_BELOW =  "android:layout_below";
				
	    public static String FilterValue(String complexStr){
	        String[] tempArr;
	        tempArr = complexStr.split("/");
			
	        return tempArr[1]; 
	        
	    }
	
	    public static String ParserXML(Context paramContext, String belowPos){
	    	String returnValue = null;
            try {
            	InputStream istream = paramContext.getAssets().open("activity_main.xml");
            	
                //InputStream istream = paramContext.getResources().openRawResource(R.layout.activity_main);
                InputSource isource = new InputSource(new InputStreamReader(istream,  "UTF-8"));
                
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(isource);
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName(strEditText);
                
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                        
                        String below_layout = eElement.getAttribute(LAYOUT_BELOW);
                        
                        if (below_layout == null || below_layout == "")
                        	break;
                        
                        if (below_layout.equalsIgnoreCase(belowPos)){
                       		if (eElement.hasAttribute(ANDROID_ID)){
                        			//System.out.println("ID: "+ eElement.getAttribute(ANDROID_ID));
                        			returnValue = FilterValue(eElement.getAttribute(ANDROID_ID));
                        			break;
                        	}
                        }
                    }
                }
            }catch (Exception e) {
                System.out.println("Catch");
                e.printStackTrace();
            }
            return returnValue;
	    }
	    
	    public static String ParserXML(Context paramContext,  String xmlfilename, String itemid){
	    	String returnValue = null;
            try {
            	InputStream istream = paramContext.getAssets().open(xmlfilename);
            	
                //InputStream istream = paramContext.getResources().openRawResource(R.layout.activity_main);
                InputSource isource = new InputSource(new InputStreamReader(istream,  "UTF-8"));
                
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(isource);
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName(strItem);
                
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        	Element eElement = (Element) nNode;
                       		if (eElement.hasAttribute(ANDROID_ID)){
                        			//System.out.println("ID: "+ eElement.getAttribute(ANDROID_ID));
                        			returnValue = FilterValue(eElement.getAttribute(ANDROID_ID));
                        			if (returnValue.equalsIgnoreCase(itemid))
                        				break;
                        	}//if
                    }//if
                }//for
            }catch (Exception e) {
                System.out.println("Catch");
                e.printStackTrace();
            }
            return returnValue;
	    }
	
	    public static String ParserXML(Context paramContext, String xmlfilename, String itemid, String tagname) {
			String returnValue = null;
            try {
            	InputStream istream = paramContext.getAssets().open(xmlfilename);
            	
                //InputStream istream = paramContext.getResources().openRawResource(R.layout.activity_main);
                InputSource isource = new InputSource(new InputStreamReader(istream,  "UTF-8"));
                
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(isource);
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName(tagname);
                
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        	Element eElement = (Element) nNode;
                       		if (eElement.hasAttribute(ANDROID_ID)){
                        			//System.out.println("ID: "+ eElement.getAttribute(ANDROID_ID));
                        			returnValue = FilterValue(eElement.getAttribute(ANDROID_ID));
                        			if (returnValue.equalsIgnoreCase(itemid))
                        				break;
                        	}//if
                    }//if
                }//for
            }catch (Exception e) {
                System.out.println("Catch");
                e.printStackTrace();
            }
            return returnValue;
		}
	    
	    public static int getIdFromAndroidUI(Context paramContext, String xmlfilename, String itemid, String tagname) {
			 //this function is to check whether this itemID exists in the .xml file with the corresponding tag name
			String strCtrlID = AndroidUIParser.ParserXML(paramContext, xmlfilename,itemid,tagname);
			
			//if ctrlID == null; there doesn't exist any item like this
			 if (strCtrlID  == null) {
				System.out.println("parse xml null");
				return -1;
			 } 
			 
			 int fieldID = -1;
			 try {
				 //we will reflect it to get ID from R id resource
				 HashMap<String, Integer> map = new  HashMap<String,Integer>();

	       	  	 @SuppressWarnings("rawtypes")
	       	  	 Class res = R.id.class; 
	       	  
	             Integer idFromMap = map.get(strCtrlID);
			     if (idFromMap==null) {
  					Field field;
  					field = res.getField(strCtrlID);
  					fieldID = field.getInt(null);
  					map.put(strCtrlID, fieldID);
			     }else {
	   					fieldID = idFromMap.intValue();
				 }	
  			 } catch (Exception e) {
  				fieldID = -1;
  			 }
			return  fieldID;
		}
	    
	    public  static int getIdFromAndroidUIWith_SureID(Context paramContext, String strCtrlID) {
			
			 int fieldID = -1;
			 try {
				 //we will reflect it to get ID from R id resource
				 HashMap<String, Integer> map = new  HashMap<String,Integer>();

	       	  	 @SuppressWarnings("rawtypes")
	       	  	 Class res = R.id.class; 
	       	  
	             Integer idFromMap = map.get(strCtrlID);
			     if (idFromMap==null) {
  					Field field;
  					field = res.getField(strCtrlID);
  					fieldID = field.getInt(null);
  					map.put(strCtrlID, fieldID);
			     }else {
	   					fieldID = idFromMap.intValue();
				 }	
  			 } catch (Exception e) {
  				fieldID = -1;
  			 }
			return  fieldID;
		}
}
